package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//儿子接口类
class Son implements Runnable {

    private IceBox iceBox; //冰箱的引用
    private Lock lock; //Lock对象

    private int bigSonNum = 0; //大儿子吃的数量
    private int smallSonNum = 0; //小儿子吃的数量

    public Son(IceBox iceBox) {
        this.iceBox = iceBox;
        lock = new ReentrantLock();
    }


    @Override
    public void run() {
        while(true){

            try {
                if(lock.tryLock(10, TimeUnit.SECONDS)){ //尝试获得锁。
                    if (IceBox.iceScreamNumber <= 0) { //冰棍吃完了。。。。
                        break; //退出循环，也就意味着线程结束...
                    }

                    IceBox.iceScreamNumber--;
                    if ("大林".equals(Thread.currentThread().getName())) {
                        System.out.println("大林吃了一根冰棍,还剩："+IceBox.iceScreamNumber+"根。");
                        bigSonNum++;
                    } else {
                        System.out.println("小林吃了一根冰棍,还剩："+IceBox.iceScreamNumber+"根。");
                        smallSonNum++;
                    }

                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                //释放锁
                lock.unlock();
            }

        }
    }

    public void showResult() {
        System.out.println("大林吃了：" + bigSonNum + "根。");
        System.out.println("小林吃了：" + smallSonNum + "根。");
    }
}
public class IceBox {

    public static int iceScreamNumber = 50; //冰箱里面的50根冰棍

    public static void main(String[] args) {

        IceBox iceBox = new IceBox(); //冰箱对象。

        Son son = new Son(iceBox); //Runnable对象

        Thread bigTh = new Thread(son, "大林"); //大儿子线程对象
        Thread smallTh = new Thread(son, "小林"); //小儿子线程对象。

        bigTh.start();  //启动大儿子线程
        smallTh.start();//启动小儿子线程

        try {

            bigTh.join(); //等待两个线程结束
            smallTh.join();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        son.showResult(); // 显示结果

    }
}
